package com.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.mapper.ClassesMapper;
import com.hzit.mapper.StudentMapper;
import com.hzit.pojo.Classes;
import com.hzit.pojo.PageResult;
import com.hzit.pojo.Student;
import com.hzit.pojo.StudentVo;
import com.hzit.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ClassesMapper classesMapper;
	//1. 展示所有学生
	@Override
	public List<Student> findAll() {
		//1.1 查询学生列表
		List<Student> students = studentMapper.selectAll();
		//1.2 为每个学生指定班级名字
		for (Student student : students) {
			Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
			student.setCname(classes.getCname());
		}
		//1.3 返回学生列表
		return students;
	}

	//2. 条件查询带分页
	@Override
	public PageResult<Student> search(int page, int pageSize, Student vo) {
		//2.1 开始分页
		PageHelper.startPage(page,pageSize);
		//2.2 开始条件查询
		//2.2.1 定义查询实例
		Example example = new Example(Student.class);
		//2.2.2 封装查询条件
		Example.Criteria criteria = example.createCriteria();
		if(vo != null){
			if(StrUtil.isNotBlank(vo.getSname())){
				criteria.andLike("sname","%" + vo.getSname() + "%");
			}
			if(StrUtil.isNotBlank(vo.getAddr())){
				criteria.andLike("addr","%" + vo.getAddr() + "%");
			}
			if(vo.getCid() != null && vo.getCid() != 0){
				criteria.andEqualTo("cid",vo.getCid());
			}
		}

		//2.2.3 开始条件查询
		List<Student> students = studentMapper.selectByExample(example);
		//2.2.4 为每个学生指定班级名字
		for (Student student : students) {
			Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
			student.setCname(classes.getCname());
		}
		//2.3 转换为Page<Student>对象
		Page<Student> studentPage = (Page<Student>) students;
		//2.4 返回
		return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
	}

	//3. 添加学生
	@Override
	public void add(Student student) {
		studentMapper.insert(student);
	}

	//4. 修改学生
	@Override
	public void update(Student student) {
		studentMapper.updateByPrimaryKey(student);
	}

	//5. 删除学生
	@Override
	public void delete(String sid) {
		studentMapper.deleteByPrimaryKey(sid);
	}
}
